package com.company;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {
    }
    TreeNode(int val) {
        this.val = val;
    }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
     }
     public TreeNode invertTree(TreeNode root) {//反转二叉树
         if(root == null){
             return null;
         }
         if(root.left == null&&root.right == null){
             return root;
         }
         TreeNode tmp = root.left;
         root.left = root.right;
         root.right = tmp;
         invertTree(root.left);
         invertTree(root.right);
         return root;
     }
     //判断两棵树是否相同
     public boolean isSameTree(TreeNode p, TreeNode q) {
         //判断两个树的结构是否一样
         if(p != null && q == null || p == null && q != null) {
             return false;
         }
         //如果第一个if 语句没有执行
         //要么都为空 要么都不为空
         if(p == null&&q == null){
             return true;
         }
         //不为空比较两个结点的值
         if(p.val!=q.val){
             return false;
         }
         return isSameTree(p.left,q.left)&&
                 isSameTree(p.right,q.right);

     }
     public boolean isSymmetric(TreeNode root) {
         if(root == null){
             return true;
         }
         return isSymmetricN(root.left,root.right);
     }
     public boolean isSymmetricN(TreeNode leftTree,TreeNode rightTree){
         if(leftTree==null&&rightTree!=null||leftTree!=null&&rightTree==null){
             return false;
         }if(leftTree==null&&rightTree==null){
             return true;
         }
         if(leftTree.val!=rightTree.val){
             return false;
         }
         return isSymmetricN(leftTree.left,rightTree.right)&&isSymmetricN(leftTree.right,rightTree.left);
     }



     public boolean isSubtree(TreeNode root, TreeNode subRoot) {
         if(root == null){
             return false;
         }
         if(isSameTree(root,subRoot)){
             return true;
         }

         return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
     }
     //判断两棵树是否相同
     public boolean isSameTree(TreeNode p, TreeNode q) {
         //判断两个树的结构是否一样
         if(p != null && q == null || p == null && q != null) {
             return false;
         }
         //如果第一个if 语句没有执行
         //要么都为空 要么都不为空
         if(p == null&&q == null){
             return true;
         }
         //不为空比较两个结点的值
         if(p.val!=q.val){
             return false;
         }

         return isSameTree(p.left,q.left)&& isSameTree(p.right,q.right);

     }
  }
